package com.yue.wx.common;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author zhengyl
 * @version date：2019年5月26日 下午8:47:28
 * @description ：
 */
public class HttpPostUploadUtil {

    public String urlStr;
    public String type;

    public HttpPostUploadUtil(String type) {
        this.type = type;
        urlStr = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="
                + GlobalConstants.access_token + "&type=" + type;
    }


    public String formUpload(String filePath) throws Exception {
        File file = new File(filePath);// 判断文件是否存在
        if (!file.exists() || !file.isFile()) {
            throw new IOException("文件不存在");
        }
        System.out.println(urlStr);
        URL urlobj = new URL(urlStr);
        // 使用HttpURLConnection连接
        HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false); // 使用post提交需 要设置忽略缓存
        con.setRequestProperty("Content-Type", "multipart/form-data;");
        // 设置请求头信息
        con.setRequestProperty("Connection", "Keep- Alive");
        con.setRequestProperty("Charset", "UTF-8");
        // 设置边界
        long currentTime = System.currentTimeMillis();
        String BOUNDARY = "---------" + currentTime;
        con.setRequestProperty("Content -Type", "multipart/ form-data; boundary=" + BOUNDARY);
        StringBuilder sb = new StringBuilder();
        sb.append("--");
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content -Di sposition: form-data ;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content - Type:applicat ion/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // 获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());// 输出表头
        out.write(head);
        // 文件正文部分
        // 把文件已流文件的方式推入到ur1中
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
        out.write(foot);
        out.flush();
        out.close();
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        try {
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            // TODO: handle finally clause
            if (reader != null) {
                reader.close();
            }
        }
        JSONObject jsonObj = JSONObject.parseObject(result);
        System.out.println(jsonObj);
        String typeName = "media_id";
        if (!"image".equals(type)) {
            typeName = type + "_media_id";
        }
        String mediaId = jsonObj.getString(typeName);// 从json中获取media_id
        return mediaId;
    }

    public static void main(String[] args) throws Exception {
        String image1 = new HttpPostUploadUtil("image").formUpload("C:\\Users\\Administrator\\Desktop\\xutai.jpg");
        String image2 = new HttpPostUploadUtil("image").formUpload("C:\\Users\\Administrator\\Desktop\\yuelin.jpg");
        System.out.println(image1);
        System.out.println(image2);
    }
}